package com.heima.crud;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

import java.util.List;

//对zookeeper节点增删改查操作
public class CRUD_Demo {
    public static void main(String[] args) throws Exception {

        //超时重连策略，每隔0.5秒重试一次，一共重试10次
        RetryPolicy retryPolicy = new RetryNTimes(10, 500);
        //构建zookeeper客户端
        /*
        newClient 参数一：ip+端口号   参数二：超时重连策略
         */
        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
        //启动客户端
        client.start();

        //新增节点
        /*
        * 参数一：节点路径  参数二：节点的内容
        * */
        // client.create().forPath("/a","bbb".getBytes());

        //新增多层节点
        //client.create().creatingParentsIfNeeded().forPath("/b/bb");

        //指定模式 withMode   永久节点  CreateMode.PERSISTENT
        //client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/c");

        //指定模式 withMode  永久有序节点  CreateMode.PERSISTENT_SEQUENTIAL
        //client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/d");

        //指定模式 withMode  临时节点 CreateMode.EPHEMERAL
        //client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/e");

        //指定模式 withMode  临时有序节点 CreateMode.EPHEMERAL_SEQUENTIAL
        //client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/f");

        //查询节点内容
        byte[] a = client.getData().forPath("/a");
        System.out.println(new String(a));

        //修改节点内容
        client.setData().forPath("/a","whatfar".getBytes());

        //查询节点内容
        byte[] a1 = client.getData().forPath("/a");
        System.out.println(new String(a1));

        //删除节点
        //client.delete().forPath("/c");

        //删除多级节点
        client.delete().deletingChildrenIfNeeded().forPath("/f");

        //查询子节点
        List<String> list = client.getChildren().forPath("/");
        System.out.println(list);

    }
}
